<template>
	<view class="language-switch">
		<picker @change="switchLanguage" :value="currentLangIndex" :range="langList" range-key="label">
			<view class="picker">
				{{ $t('message.switchLang') }}: {{ currentLangText }}
			</view>
		</picker>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				langList: [{
						code: 'zh-CN',
						label: '中文'
					},
					{
						code: 'en-US',
						label: 'English'
					}
				]
			}
		},
		computed: {
			currentLangIndex() {
				return this.langList.findIndex(item => item.code === this.$i18n.locale)
			},
			currentLangText() {
				return this.langList[this.currentLangIndex].label
			}
		},
		methods: {
			switchLanguage(e) {
				const langCode = this.langList[e.detail.value].code
				this.$i18n.locale = langCode

				// 保存语言设置到本地存储
				uni.setStorageSync('language', langCode)

				// 提示语言已切换
				uni.showToast({
					title: this.$t('tips.languageChanged'),
					icon: 'none'
				})
			}
		}
	}
</script>

<style>
	.language-switch {
		padding: 15px;
		background-color: #f8f8f8;
		border-radius: 8px;
		margin: 15px;
	}

	.picker {
		color: #333;
		font-size: 16px;
	}
</style>